package com.demo.uitls;

import com.alibaba.fastjson.JSON;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;
import com.aliyun.mns.model.RawTopicMessage;
import com.aliyun.mns.model.TopicMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2015/3/15.
 */
public class MNSClientHelper {
    private Logger logger = LoggerFactory.getLogger(getClass());

    public static final int DEFAULT_DELAY_SECONDS = 0;

    private String accessId;
    private String accessKey;
    private String endpoint;
    private MNSClient client;

    public void setAccessId(String accessId) {
        this.accessId = accessId;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessId() {
        return accessId;
    }
    public String getAccessKey() {
        return accessKey;
    }

    public String getEndpoint() {
        return endpoint;
    }

    private void initClient() {
        CloudAccount account = new CloudAccount(accessId, accessKey, endpoint);
        try {
            if (client == null) {
                client = account.getMNSClient();
                logger.debug("MNS|初始化mnsClient");
            }
        } catch (Exception e) {
            logger.error("MNS|初始化错误", e);
        }
    }

    private void destroy() {
        try {
            if (client != null) {
                logger.debug("MNS|销毁mnsClient");
                client.close();
            }
        } catch (Exception e) {
            logger.error("MNS|关闭错误", e);
        }
    }

    public MNSClient getClient() {
        if (client == null) {
            logger.debug("MNS|client为null");
            initClient();
        } else if (!client.isOpen()) {
            logger.debug("MNS|client is not open");
            client.close();
            client = null;
            initClient();
        }
        return client;
    }

    public boolean sendMsg(String queueName, String content) {
        return sendMsg(queueName, content, DEFAULT_DELAY_SECONDS);
    }

    public boolean sendMsg(String queueName, String content, int delaySeconds) {
        try {
            CloudQueue queue = getClient().getQueueRef(queueName);

            Message message = new Message();
            message.setMessageBody(content);
            message.setDelaySeconds(delaySeconds);
            queue.putMessage(message);
            return true;
        } catch (Exception e) {
            logger.warn(String.format("MNS|插入错误queueName %s  content %s", queueName, content), e);
        }
        return false;
    }

    public Message pop(String qName) {
        return getClient().getQueueRef(qName).popMessage();
    }


    /**
     * 发送主题消息
     * Send topic message boolean.
     *
     * @param topicName the topic name
     * @param content   the content
     * @return the boolean
     */
    public boolean sendTopicMessage(String topicName, String content) {
        return sendTopicMessage(topicName, content, null);
    }

    /**
     * 发送带tag主题消息
     * Send topic obj message boolean.
     *
     * @param topicName the topic name
     * @param content   the content
     * @param tag       the tag
     * @return the boolean
     */
    public boolean sendTopicObjMessage(String topicName, Object content, String tag) {
        return sendTopicMessage(topicName, JSON.toJSONString(content), tag);
    }

    public boolean sendTopicMessage(String topicName, String content, String tag) {
        try {
            CloudTopic topic = getClient().getTopicRef(topicName);
            TopicMessage msg = new RawTopicMessage(); //可以使用TopicMessage结构，选择不进行Base64加密
            msg.setMessageBody(content);
            if (StringUtils.isNotEmpty(tag)) {
                msg.setMessageTag(tag);
            }
            topic.publishMessage(msg);
            return true;
        } catch (Exception e) {
            logger.warn("publishTopicMessage|插入错误", e);
        }
        return false;
    }
}
